import { ref } from 'vue';
import type { ISerachItem } from './types';
import { getHotCompany, type ISearchParams, searchCompany } from '../apis';

export const LOCALSTORAGE_KEY_SEARCH_HISTORY = 'search-history';

/** 搜索历史hook */
export function useSearchHistory() {
  const searchHistoryList = ref<Array<ISerachItem>>([]);
  const getSearchHistoryList = () => {
    const local = localStorage.getItem(LOCALSTORAGE_KEY_SEARCH_HISTORY);
    searchHistoryList.value = local ? JSON.parse(local) : [];
  };
  const setSearchHistory = (item: ISerachItem) => {
    const i = searchHistoryList.value.findIndex((s) => s.id === item.id);
    if (searchHistoryList.value.length === 20) {
      if (i > -1) searchHistoryList.value.splice(i, 1);
      else searchHistoryList.value.pop();
    } else {
      if (i > -1) searchHistoryList.value.splice(i, 1);
    }
    searchHistoryList.value.unshift({
      id: item.id,
      /** 去除所有em标签 */
      name: item.name.replaceAll(/<[^>]+>/g, '')
    });
    localStorage.setItem(LOCALSTORAGE_KEY_SEARCH_HISTORY, JSON.stringify(searchHistoryList.value));
  };
  const removeSearchHistory = () => {
    localStorage.removeItem(LOCALSTORAGE_KEY_SEARCH_HISTORY);
    searchHistoryList.value = [];
  };

  return {
    searchHistoryList,
    getSearchHistoryList,
    setSearchHistory,
    removeSearchHistory
  };
}

/** 热门搜索hook */
export function useHotSearch() {
  const hotSearchList = ref<Array<ISerachItem>>([]);
  const getHotSearchList = async () => {
    hotSearchList.value = await getHotCompany();
  };

  return {
    hotSearchList,
    getHotSearchList
  };
}

/** 企业搜索hook */
export function useCompanySearch() {
  const loading = ref(false);
  const hasMore = ref(true);
  const searchParams = $ref<ISearchParams>({
    wd: '',
    limit: 20,
    offset: 0
  });
  const searchResultList = ref<Array<ISerachItem>>([]);
  const getSearchResultList = async () => {
    try {
      loading.value = true;
      const res = await searchCompany(searchParams);
      searchResultList.value = [...searchResultList.value, ...res.items];
      searchParams.offset += res.items.length;
      loading.value = false;
      if (res.items.length < searchParams.limit) {
        hasMore.value = false;
      }
    } catch {
      loading.value = false;
      searchResultList.value = [];
    }
  };

  return {
    loading,
    hasMore,
    searchParams,
    searchResultList,
    getSearchResultList
  };
}
